﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Globalization;

namespace wfaFoxMigrator
{
    public partial class frmConfiguration : Form
    {
        public string destinationDBOracle 
        {
            get {return String.Format(Properties.Settings.Default.OracleCS, txtDestDS.Text, txtDestUser.Text, txtDestPwd.Text); }
        }
        CultureInfo[] allCultures;
        public delegate void OnPathChange(string newPath);
        public event OnPathChange PathChanger;
        public frmConfiguration()
        {
            InitializeComponent();
            loadInitialValues();
        }

        #region Private Methods
        private void loadInitialValues()
        {
            enumerateAllCultures();
            fillUpDataBaseCombo(Properties.Settings.Default.CurrentDB);
            fillUpDataBaseComboDest(Properties.Settings.Default.CurrentDBDest);
            txtInitialPath.Text = Properties.Settings.Default.InitialPath;
            chkJetEnabled.Checked = Properties.Settings.Default.UseJetProvider;
            chbGenerateSchema.Checked = Properties.Settings.Default.CreateSchema;
            chbTransferData.Checked = Properties.Settings.Default.TransferData;
            txtDataSource.Text = Properties.Settings.Default.DataSource;
            txtUser.Text = Properties.Settings.Default.User;
            txtPwd.Text = Properties.Settings.Default.Password;
            txtInitialCatalog.Text = Properties.Settings.Default.InitialCatalog;
            txtDestDS.Text = Properties.Settings.Default.DataSourceDest;
            txtDestUser.Text = Properties.Settings.Default.UserDest;
            txtDestPwd.Text = Properties.Settings.Default.PasswordDest;
            txtDestInitialCatalog.Text = Properties.Settings.Default.InitialCatalogDest;
            txtTextFilePath.Text = Properties.Settings.Default.TextFilePath;            
            txtMapFilesPath.Text = Properties.Settings.Default.MapFilesPath;
            if (Properties.Settings.Default.CurrentCulture.Equals("es-CO"))
                cboCultures.FindString("User Defined");
            else
                cboCultures.FindString(Properties.Settings.Default.CurrentCulture);
            txtDateFormat.Text = Properties.Settings.Default.DateFormat;
            txtTimeFormat.Text = Properties.Settings.Default.TimeFormat;
            txtNumberDecimalSep.Text = Properties.Settings.Default.NumberDecimalSep;
            txtNumberGroupSep.Text = Properties.Settings.Default.NumberGroupSep;
            txtCurrencyDecimalSep.Text = Properties.Settings.Default.CurrencyDecimalSep;
            txtCurrencyGroupSep.Text = Properties.Settings.Default.CurrencyGroupSep;
            chkUseBulkInsert.Checked = Properties.Settings.Default.UseBulkInsert;
        }
        #endregion        

        #region Events related to controls        
        private void fillUpDataBaseCombo(string DestinyDB)
        {
            cboDatabase.Items.Clear();
            foreach (DBEnumerators dbe in Enum.GetValues(typeof(DBEnumerators)))
            {
                cboDatabase.Items.Add(dbe.ToString());
                if (dbe.ToString().Equals(DestinyDB))
                {
                    cboDatabase.SelectedIndex = cboDatabase.FindStringExact(DestinyDB);
                }                
            }
        }
        private void fillUpDataBaseComboDest(string DestinyDB)
        {
            cboDestDB.Items.Clear();
            foreach (DBEnumerators dbe in Enum.GetValues(typeof(DBEnumerators)))
            {
                cboDestDB.Items.Add(dbe.ToString());
                if (dbe.ToString().Equals(DestinyDB))
                {
                    cboDestDB.SelectedIndex = cboDestDB.FindStringExact(DestinyDB);
                }
            }
        }
        private void btnGetDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFileDialog = new FolderBrowserDialog();
            openFileDialog.SelectedPath = txtInitialPath.Text;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtInitialPath.Text = openFileDialog.SelectedPath;                
            }           
        }
        private void btnTestConn_Click(object sender, EventArgs e)
        {
            saveSettings();
            string message = string.Empty;
            bool connectionSuccess = true;
            string strSql = CommonFunctions.GetTestQuery();
            string constr = CommonFunctions.GetCurrentCS();
            try
            {
                using (System.Data.OleDb.OleDbConnection fpConn = new OleDbConnection(constr))
                {
                    fpConn.Open();
                    OleDbCommand fpComm = new OleDbCommand(strSql, fpConn);
                    OleDbDataReader fpRdr = fpComm.ExecuteReader();
                    fpConn.Close();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                connectionSuccess = false;                
            }
            if (connectionSuccess)
            {
                MessageBox.Show(Properties.Settings.Default.ConnectionSuccess);                
            }
            else
            {
                MessageBox.Show(String.Format(Properties.Settings.Default.ConnectionFailure,message));
            }
        }        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnAccept_Click(object sender, EventArgs e)
        {
            saveSettings();
            OnPathChangeEvent(this.txtInitialPath.Text);
            this.Close();
        }

        private void saveSettings()
        {
            if (Properties.Settings.Default.InitialPath != txtInitialPath.Text)
            {
                OnPathChangeEvent(txtInitialPath.Text);
            }
            Properties.Settings.Default.InitialPath = txtInitialPath.Text;
            Properties.Settings.Default.CurrentDB = cboDatabase.SelectedItem.ToString();
            Properties.Settings.Default.DataSource = txtDataSource.Text;
            Properties.Settings.Default.User = txtUser.Text;
            Properties.Settings.Default.Password = txtPwd.Text;
            Properties.Settings.Default.CurrentDBDest = cboDestDB.SelectedItem.ToString();
            Properties.Settings.Default.DataSourceDest = txtDestDS.Text;
            Properties.Settings.Default.UserDest = txtDestUser.Text;
            Properties.Settings.Default.PasswordDest = txtDestUser.Text;
            Properties.Settings.Default.UseJetProvider = chkJetEnabled.Checked;
            Properties.Settings.Default.CreateSchema = chbGenerateSchema.Checked;
            Properties.Settings.Default.TransferData = chbTransferData.Checked;
            Properties.Settings.Default.InitialCatalog = txtInitialCatalog.Text;
            Properties.Settings.Default.MapFilesPath = txtMapFilesPath.Text;
            Properties.Settings.Default.TextFilePath = txtTextFilePath.Text;
            Properties.Settings.Default.CurrentCulture = cboCultures.SelectedText.Equals("User Defined") ? "es-CO" : cboCultures.SelectedText;
            Properties.Settings.Default.DateFormat = txtDateFormat.Text;
            Properties.Settings.Default.TimeFormat = txtTimeFormat.Text;
            Properties.Settings.Default.NumberDecimalSep = txtNumberDecimalSep.Text;
            Properties.Settings.Default.NumberGroupSep = txtNumberGroupSep.Text;
            Properties.Settings.Default.CurrencyDecimalSep = txtCurrencyDecimalSep.Text;
            Properties.Settings.Default.CurrencyGroupSep = txtCurrencyGroupSep.Text;
            Properties.Settings.Default.UseBulkInsert = chkUseBulkInsert.Checked;
            Properties.Settings.Default.Save();
        }
        private void btnTextFilesPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFileDialog = new FolderBrowserDialog();
            openFileDialog.SelectedPath = txtTextFilePath.Text;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtTextFilePath.Text = openFileDialog.SelectedPath;
            }
        }
        #endregion        

        private void cboDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtInitialCatalog.Enabled = cboDatabase.SelectedItem.ToString().Equals("SqlServer");
        }

        protected void OnPathChangeEvent(string path)
        {
            if (PathChanger != null)
            {
                PathChanger(path);                
            }
        }
        private void enumerateAllCultures()
        {
            cboCultures.Items.Clear();
            cboCultures.Items.Add("User Defined");
            cboCultures.SelectedItem = 0;
            CultureTypes[] mostCultureTypes = new CultureTypes[] {
                        //CultureTypes.NeutralCultures, 
                        CultureTypes.SpecificCultures//, 
                        //CultureTypes.InstalledWin32Cultures, 
                        //CultureTypes.UserCustomCulture, 
                        //CultureTypes.ReplacementCultures
                        };
            // Get and enumerate all cultures.
            allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
            foreach (CultureInfo ci in allCultures.OrderBy(c => c.Name))
            {
                cboCultures.Items.Add(ci.Name);                
            }
        }

        private void cboCultures_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!cboCultures.SelectedItem.ToString().Equals("User Defined"))
            {
                CultureInfo ci = allCultures.Where(c => c.Name.Equals(cboCultures.SelectedText)).FirstOrDefault();
                txtDateFormat.Text = ci.DateTimeFormat.ShortDatePattern;
                txtTimeFormat.Text = ci.DateTimeFormat.ShortTimePattern;
                txtCurrencyDecimalSep.Text = ci.NumberFormat.CurrencyDecimalSeparator;
                txtCurrencyGroupSep.Text = ci.NumberFormat.CurrencyGroupSeparator;
                txtNumberDecimalSep.Text = ci.NumberFormat.NumberDecimalSeparator;
                txtNumberGroupSep.Text = ci.NumberFormat.NumberGroupSeparator;
            }
            else
            {
                if (Properties.Settings.Default.CurrentCulture.Equals("es-CO"))
                    cboCultures.FindString("User Defined");
                else
                    cboCultures.FindString(Properties.Settings.Default.CurrentCulture);
                txtDateFormat.Text = Properties.Settings.Default.DateFormat;
                txtTimeFormat.Text = Properties.Settings.Default.TimeFormat;
                txtNumberDecimalSep.Text = Properties.Settings.Default.NumberDecimalSep;
                txtNumberGroupSep.Text = Properties.Settings.Default.NumberGroupSep;
                txtCurrencyDecimalSep.Text = Properties.Settings.Default.CurrencyDecimalSep;
                txtCurrencyGroupSep.Text = Properties.Settings.Default.CurrencyGroupSep;
            }
        }

        private void btnMapFilesPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFileDialog = new FolderBrowserDialog();
            openFileDialog.SelectedPath = txtMapFilesPath.Text;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtMapFilesPath.Text = openFileDialog.SelectedPath;
            }
        }

        private void btnTestDestDB_Click(object sender, EventArgs e)
        {
            saveSettings();
            string message = string.Empty;
            bool connectionSuccess = true;
            string strSql = CommonFunctions.GetTestQuery();
            string constr = CommonFunctions.GetCurrentCSDest();
            try
            {
                using (System.Data.OleDb.OleDbConnection fpConn = new OleDbConnection(constr))
                {
                    fpConn.Open();
                    OleDbCommand fpComm = new OleDbCommand(strSql, fpConn);
                    OleDbDataReader fpRdr = fpComm.ExecuteReader();
                    fpConn.Close();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                connectionSuccess = false;
            }
            if (connectionSuccess)
            {
                MessageBox.Show(Properties.Settings.Default.ConnectionSuccess);
            }
            else
            {
                MessageBox.Show(String.Format(Properties.Settings.Default.ConnectionFailure, message));
            }
        }

        private void cboDestDB_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtDestInitialCatalog.Enabled = cboDestDB.SelectedItem.ToString().Equals("SqlServer");
        }
    }
}
